package com.fitness.servlet;

import com.fitness.dao.MemberDAO;
import com.fitness.entity.Member;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/MemberServlet")
public class MemberServlet extends HttpServlet {

    private final MemberDAO memberDAO = new MemberDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少 action 参数");
            return;
        }

        // 1. 处理【查询列表】逻辑
        if ("list".equals(action)) {
            List<Member> memberList = memberDAO.getMemberList();
            request.setAttribute("memberList", memberList);
            request.getRequestDispatcher("WEB-INF/views/admin/memberList.jsp").forward(request, response);
        }
        // 2. 处理【删除】逻辑
        else if ("delete".equals(action)) {
            try {
                int memberId = Integer.parseInt(request.getParameter("memberId"));
                boolean success = memberDAO.deleteMember(memberId);
                if (success) {
                    response.sendRedirect("MemberServlet?action=list");
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "删除失败");
                }
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的会员 ID");
            }
        }
        else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "不支持的 action：" + action);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if (action == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少 action 参数");
            return;
        }

        // 处理【新增】逻辑
        if ("add".equals(action)) {
            try {
                // 1. 接收表单参数
                String memberName = request.getParameter("memberName");
                String phone = request.getParameter("phone");

                // 2. 验证参数
                if (memberName == null || memberName.isEmpty() || phone == null || phone.isEmpty()) {
                    request.setAttribute("errorMsg", "会员姓名和联系电话不能为空！");
                    forwardToListPage(request, response);
                    return;
                }

                // 3. 封装实体（默认积分0，等级普通会员）
                Member member = new Member();
                member.setMemberName(memberName);
                member.setPhone(phone);
                member.setPoints(0);
                member.setMembershipLevel("普通会员");
                member.setDiscountRate(1.0);

                // 4. 插入新会员
                boolean success = memberDAO.insertMember(member);
                if (success) {
                    response.sendRedirect("MemberServlet?action=list");
                } else {
                    request.setAttribute("errorMsg", "新增会员失败，请稍后再试！");
                    forwardToListPage(request, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("errorMsg", "系统错误，新增会员失败！");
                forwardToListPage(request, response);
            }
        }
        else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "不支持的 action：" + action);
        }
    }

    // 转发回列表页并显示错误信息
    private void forwardToListPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("memberList", memberDAO.getMemberList());
        request.getRequestDispatcher("WEB-INF/views/admin/memberList.jsp").forward(request, response);
    }
}